package com.facexue.miniprogram.utils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {
	private static final String SECRET = "facexue_admin_user";
	
	/**
	 * 生成Token
	 * @param paramMap 生成Token的数据
	 * @return 生成的Token
	 */
	public static String createToken (Map<String, String> paramMap) {
		Map<String,Object> headMap = new HashMap();
		Calendar expireTime = Calendar.getInstance();
        // 过期时间默认是 7 天
        expireTime.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        // Header(使用默认数据，故map没有值，可以省略)
        builder.withHeader(headMap);
        // Payload
        paramMap.forEach((key, value) -> {
            builder.withClaim(key, value);
        });
        // 过期时间
        String token = builder.withExpiresAt(expireTime.getTime())
                // Signature
                .sign(Algorithm.HMAC256(SECRET));
        return token;
	}
	/**
	 * 验证Token的合法性
	 * @param token
	 */
	public static void verify(String token) {
		JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
	}
	/**
	 * 获取Token的信息
	 * @param token
	 * @return
	 */
	public static DecodedJWT getTokenInfo(String token) {
		return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
	}
}
